<?php

namespace app\admin\controller\wx;

use app\admin\model\halt\Cate;
use app\common\controller\Backend;
use think\Config;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Wxpro extends Backend
{
    
    /**
     * Wxpro模型对象
     * @var \app\admin\model\Wxpro
     */
    protected $model = null;
    protected $modelProduct = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Wxpro;
        $this->modelProduct = new \app\admin\model\Wxproduct();
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("FenleiList", $this->model->getFenleiList());
        //获取配置
        $config = Config::get('wxproduct');
        $this->assignConfig('wxProductType',!isset($config['type']) ? '':$config['type']);
        $this->view->assign("wxProductType", !isset($config['type']) ? '':json_decode($config['type'],true));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $this->searchFields = 'id,name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field].'  ('.$item['type_text'].'--'.$item['kg'].') ' : ''
                ];
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $count = 0;
                $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                foreach ($list as $index => $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save($values);
                }
                if ($count) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
        }
    }

    public function import()
    {
//        parent::import();
        $this->import_update();
    }

    /**
     * 分类科目版本
     * @return string
     * @throws \think\Exception
     */
    public function config($ids = null)
    {
        if($data = $this->request->post('row/a'))
        {
            $this->modelProduct->setConfig($data,'typekemubanben');
            $Array = [];
            foreach (explode(',',$ids) as $item)
            {
                if($data['fenlei'] > 1)
                {
                    $Array[] = [
                        'id'=>$item,
                        'fenlei'=>$data['fenlei'],
                        'kemu'=>$data['kemu'],
                        'banben'=>$data['banben'],
                    ];
                }
                if($data['ministrial'])
                {
                    {
                        $Array[] = [
                            'id'=>$item,
                            'ministrial'=>$data['ministrial'],
                        ];
                    }
                }
            }
            if (!$Array) {
                $this->error(__('No rows were updated'));
            }
            try {
                $this->model->saveAll($Array);
            } catch (\think\exception\PDOException $exception) {
                $this->error($exception->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('修改成功');
        }
        //获取配置
        $config = Config::get('typekemubanben');
        $config['fenlei'] = '';
        $config['kemu'] = '';
        $config['banben'] = '';
        $this->view->assign('configs',$config);
        return $this->view->fetch();
    }


    protected function import_update(){

        $file = $this->request->request('file');

        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);

        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;

                }
            }
            if ($row) {
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        /*$count = 0;
        foreach ($insert  as $value)
        {
            $list = $this->model->where('code','=',$value['code'])->select();
            foreach ($list as $value2)
            {
                $value2->ministrial = $value['ministrial'];
                $count +=$value2->save();
            }
        }
        echo $count;exit;*/
        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

    /**
     * 数据同步
     */
    public function copys($ids = null)
    {
        if(!$params = $this->request->request('params'))
        {
            $this->error('请输入“要替换”或“替换为”的内容。');
        }
        $params = explode(',',$params);
        $array = [];
        $list = collection($this->model->where("id",'in',$ids)->select())->toArray();
        foreach ($list as $item)
        {
            $item = array_filter($item);
            unset($item['id'],$item['code'],$item['type_text'],$item['fenlei_text'],$item['kemu_text'],$item['banben_text']);
            $item['name'] = str_replace($params[0],trim($params[1]?$params[1]:''),$item['name']);
            if(!$this->model->get(['name'=>$item['name']])) $array[] = $item;
        }
        $result = $this->model->saveAll($array);
        if ($result) {
            $count = count($array);
            $this->success("复制成功{$count}条");
        } else {
            $this->error(__('No rows were updated').'不能有重复的名称！');
        }
    }

    public function adds($ids = null)
    {
        if(!$params = $this->request->request('params'))
        {
            $this->error('请输入“码洋”。');
        }
        $list = collection((array)$this->model->where('id', 'in', $ids)->select())->toArray();
        $data = [];
        foreach ($list as $item)
        {
            if(!$row = $this->modelProduct->get(['name'=>$item['name']])){
                $data[] = [
                    'name'=>$item['name'],
                    'kg'=>$item['kg'] ? $item['kg']:'',
                    'ministrial'=>$params,
                    'type'=>$item['type'] ? $item['type']:'',
                    'unit'=>1,
                    'wxpro_ids'=>$item['id']
                ];
            }else{
                $row->name = $item['name'];
                $row->kg = $item['kg'];
                $row->wxpro_ids = $item['id'];
                $row->save();
            }
        }
        $result = $this->modelProduct->saveAll($data);
        if ($result) {
            $count = count($data);
            $this->success("成品添加成功{$count}条");
        } else {
            $this->error(__('No rows were updated').'不能有重复的名称！');
        }
    }

}
